package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.adapter.RedeemCodeAdapter;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.model.RedeemCodeObject;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;

public class RedeemCodeActivity extends Activity implements OnItemClickListener, Receiver, TextWatcher, android.view.View.OnClickListener, OnKeyListener {

	private TextView qrCode;
	private static final int TYPE_CODE_MAUALLY = 27;
	private DetachableResultReceiver receiver;
	private ProgressDialog progress;
	private Intent checkRedeemIntent;
	private TextView redeem_code_message;
	private LayoutInflater mInflater;
	private View layout;
	private EditText code_manual1;
	private EditText code_manual2;
	private EditText code_manual3;
	private EditText code_manual4;
	private EditText code_manual5;
	private View currentView = code_manual1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.redeem_code);
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		checkRedeemIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		qrCode = (TextView) findViewById(R.id.redeem_code);
		redeem_code_message = (TextView) findViewById(R.id.redeem_code_message);
		ListView list = (ListView) findViewById(R.id.list_redeem);
		ListAdapter adapter = new RedeemCodeAdapter(getApplicationContext(), R.layout.redeem_code_item, new String[2]);
		list.setAdapter(adapter);
		list.setOnItemClickListener(this);

	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				String contents = intent.getStringExtra("SCAN_RESULT");
				qrCode.setVisibility(View.VISIBLE);
				qrCode.setText(contents);
				showDialogQrCode(contents);
			} else if (resultCode == RESULT_CANCELED) {
			}
		}
	}

	public void checkRedeemCode() {
		String redeemCode = qrCode.getText().toString().trim();
		// TODO
		// redeemCode = "KKH5F-5PFQ7-7LQBW-JDWF7-GVQGL";
		checkRedeemIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		checkRedeemIntent.putExtra(Keys._redeemCode, redeemCode);
		checkRedeemIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.REDEEM_CHECK);
		startService(checkRedeemIntent);
	}

	private void showDial(String message) {
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setMessage(message);
		builder1.setPositiveButton(getString(R.string.ok), new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				String redeemCode = qrCode.getText().toString().trim();
				Log.v("redeemCode", redeemCode);

				checkRedeemIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
				checkRedeemIntent.putExtra(Keys._redeemCode, redeemCode);
				checkRedeemIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.REDEEM_CONSUME);
				startService(checkRedeemIntent);
			}
		});
		builder1.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder1.create();
		builder1.show();
	}

	// TODO
	@Override
	public void onClick(View v) {
		currentView = v;
	}

	@Override
	public void afterTextChanged(Editable s) {
		if (currentView == null)
			currentView = code_manual1;
		if (s.length() == 5) {
			switch (currentView.getId()) {
			case R.id.code_manual1:
				code_manual2.requestFocus();
				currentView = code_manual2;
				break;
			case R.id.code_manual2:
				code_manual3.requestFocus();
				currentView = code_manual3;
				break;
			case R.id.code_manual3:
				code_manual4.requestFocus();
				currentView = code_manual4;
				break;
			case R.id.code_manual4:
				code_manual5.requestFocus();
				currentView = code_manual5;
				break;
			case R.id.code_manual5:
				//currentView = code_manual1;
				//code_manual1.requestFocus();
				break;
			default:
				break;
			}
		}

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case TYPE_CODE_MAUALLY:

			layout = mInflater.inflate(R.layout.type_code_manually, null);
			code_manual1 = (EditText) layout.findViewById(R.id.code_manual1);
			code_manual1.addTextChangedListener(this);
			code_manual1.setOnClickListener(this);
			code_manual1.setOnKeyListener(this);
			code_manual2 = (EditText) layout.findViewById(R.id.code_manual2);
			code_manual2.addTextChangedListener(this);
			code_manual2.setOnClickListener(this);
			code_manual2.setOnKeyListener(this);
			code_manual3 = (EditText) layout.findViewById(R.id.code_manual3);
			code_manual3.addTextChangedListener(this);
			code_manual3.setOnClickListener(this);
			code_manual3.setOnKeyListener(this);
			code_manual4 = (EditText) layout.findViewById(R.id.code_manual4);
			code_manual4.addTextChangedListener(this);
			code_manual4.setOnClickListener(this);
			code_manual4.setOnKeyListener(this);
			code_manual5 = (EditText) layout.findViewById(R.id.code_manual5);
			code_manual5.addTextChangedListener(this);
			code_manual5.setOnClickListener(this);
			code_manual5.setOnKeyListener(this);

			builder.setView(layout);
			builder.setMessage(getString(R.string.input_code));
			builder.setPositiveButton(getString(R.string.ok), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					qrCode.setVisibility(View.VISIBLE);
					String code = code_manual1.getText().toString().trim() + "-" + code_manual2.getText().toString().trim() + "-"
							+ code_manual3.getText().toString().trim() + "-" + code_manual4.getText().toString().trim() + "-"
							+ code_manual5.getText().toString().trim();
					qrCode.setText(code);
					removeDialog(TYPE_CODE_MAUALLY);
					checkRedeemCode();
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(TYPE_CODE_MAUALLY);
				}
			});

			builder.setCancelable(true);
			return builder.create();
		}
		return null;
	}

	private void showDialogQrCode(final String qrValue) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		layout = mInflater.inflate(R.layout.type_code_manually, null);
		code_manual1 = (EditText) layout.findViewById(R.id.code_manual1);
		code_manual1.addTextChangedListener(this);
		code_manual1.setOnClickListener(this);
		code_manual1.setOnKeyListener(this);
		code_manual2 = (EditText) layout.findViewById(R.id.code_manual2);
		code_manual2.addTextChangedListener(this);
		code_manual2.setOnClickListener(this);
		code_manual2.setOnKeyListener(this);
		code_manual3 = (EditText) layout.findViewById(R.id.code_manual3);
		code_manual3.addTextChangedListener(this);
		code_manual3.setOnClickListener(this);
		code_manual3.setOnKeyListener(this);
		code_manual4 = (EditText) layout.findViewById(R.id.code_manual4);
		code_manual4.addTextChangedListener(this);
		code_manual4.setOnClickListener(this);
		code_manual4.setOnKeyListener(this);
		code_manual5 = (EditText) layout.findViewById(R.id.code_manual5);
		code_manual5.addTextChangedListener(this);
		code_manual5.setOnClickListener(this);
		code_manual5.setOnKeyListener(this);

		builder.setView(layout);
		builder.setMessage(getString(R.string.input_code));

		String[] arr = qrValue.split("-");

		try {
			code_manual1.setText(arr[0]);
		} catch (Exception e) {
		}
		try {
			code_manual2.setText(arr[1]);
		} catch (Exception e) {
		}

		try {
			code_manual3.setText(arr[2]);
		} catch (Exception e) {
		}
		try {
			code_manual4.setText(arr[3]);
		} catch (Exception e) {
		}
		try {
			code_manual5.setText(arr[4]);
		} catch (Exception e) {
		}

		builder.setPositiveButton(getString(R.string.ok), new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				qrCode.setVisibility(View.VISIBLE);
				qrCode.setText(qrValue);
				checkRedeemCode();

			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		builder.setCancelable(true);
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
		// return;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent;
		switch (position) {
		case 0:
			showDialog(TYPE_CODE_MAUALLY);
			break;
		case 1:
			intent = new Intent("com.google.zxing.client.android.SCAN");
			intent.setPackage("com.warrantyhotel.android");
			intent.putExtra("SCAN_MODE", "QR_CODE_MODE,ONE_D_MODE");
			startActivityForResult(intent, 0);
			break;
		default:
			break;
		}
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			break;
		case UpdateIntentService.STATUS_ERROR:
			if (null != progress)
				progress.dismiss();
			// ToastUtil.showText(getApplicationContext(),
			// resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			break;

		case UpdateIntentService.STATUS_FINISHED:
			if (null != progress)
				progress.dismiss();
			if (resultData.containsKey(Keys.actionIdentificator) && resultData.getInt(Keys.actionIdentificator) == QueriesCodes.REDEEM_CHECK) {
				RedeemCodeObject redeemCode = resultData.getParcelable(Keys._redeemCode);
				if (redeemCode.getMessageCode() == 2048008) {
					// showDialog(CONFIRM);
					showDial(redeemCode.getMessage());
				} else {
					redeem_code_message.setText(redeemCode.getMessage());
				}
			} else if (resultData.containsKey(Keys.actionIdentificator) && resultData.getInt(Keys.actionIdentificator) == QueriesCodes.REDEEM_CONSUME) {
				RedeemCodeObject redeemCode = resultData.getParcelable(Keys._redeemCode);
				redeem_code_message.setText("");
				redeem_code_message.setText(redeemCode.getMessage());
				switch (redeemCode.getMessageCode()) {
				case 2048007:

					break;
				case 2048006:

					break;
				case 2049001:

					break;

				default:
					break;
				}
			}
			break;
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_DEL && KeyEvent.ACTION_UP == event.getAction()) {
			if (TextUtils.isEmpty(((EditText) v).getText())) {
				switch (v.getId()) {
				case R.id.code_manual1:
					// code_manual2.requestFocus();
					break;
				case R.id.code_manual2:
					code_manual1.requestFocus();
					currentView = code_manual1;
					code_manual1.setSelection(code_manual1.getText().length());
					break;
				case R.id.code_manual3:
					code_manual2.requestFocus();
					currentView = code_manual2;
					code_manual2.setSelection(code_manual2.getText().length());
					break;
				case R.id.code_manual4:
					code_manual3.requestFocus();
					currentView = code_manual3;
					code_manual3.setSelection(code_manual3.getText().length());
					break;
				case R.id.code_manual5:
					code_manual4.requestFocus();
					currentView = code_manual4;
					code_manual4.setSelection(code_manual4.getText().length());
					break;
				default:
					break;
				}
			}
		}
		return false;
	}

}